
package com.jstyle.beatecg.util;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;

import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.daoManager.HrvDataDaoManager;
import com.jstyle.beatecg.daoManager.UserInfoDaoManager;
import com.jstyle.beatecg.model.HrvData;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.model.UserInfo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;





/**
 * Created by Administrator on 2019/8/1.
 */


public class PdfUtils {
    static int maxXSize=2540;
    //final static float totalWidth = 1040;
    final static float totalWidth = (PageSize.A4.getHeight()/297)*250;//画心率格子总的宽度
    final static float length=totalWidth/50f;//每个大格子的宽度
    static float totalHeight;
    static float   col ;
    static float endbottom= length*4;
    static float   starY=length;//开始的Y轴
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static void createFile(String path, List<Integer>data, String date) {
        try {
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(path));
            Document document=new Document(pdfDocument,PageSize.A4.rotate());
            document.setBackgroundColor(new DeviceRgb(255, 255, 255));
            int size = data.size();
           // col = size % maxXSize == 0 ? size / maxXSize : size / maxXSize + 1;//一次画5120个点，分多少次画
            col=5;
            float height = length;
            float width = length;
            totalHeight = col * height * 6;//一次需要6个高度
            PageSize pageSize = new PageSize(PageSize.A4.getHeight(), PageSize.A4.getWidth());


            // 8270, 11690
            PdfPage pdfPage = pdfDocument.addNewPage(pageSize);
            PdfCanvas pdfCanvas = new PdfCanvas(pdfPage);
            Color colorLinemin = new DeviceRgb(255, 182, 193);
            Color colorS=new DeviceRgb(255, 0, 0);
            float startX = 0f;
            float startY = starY;
            float endX = totalWidth;
            float endY = totalHeight;

            addParagraph(  document,pdfCanvas,date,totalHeight+(595/210)*30);//预留30厘米的搞显示类容
            pdfCanvas.stroke();
            pdfCanvas.setStrokeColor(colorLinemin).setLineWidth(0.3f);
            //绘制小网格竖线
            for (int i = 0; i < 50*5; i++) {
                pdfCanvas.moveTo((i * width+startY)/5+length+length*5, length+endbottom)
                        .lineTo((i * width+startY)/5+length+length*5, (endY+length+endbottom));
            }

            //小网格横线
            for (int i = 0; i <= (col * 6)*5-1; i++) {
                pdfCanvas.moveTo(startX+startY+length*5, (i * height+startY)/5+length+endbottom)
                        .lineTo(endX+startY+length*5, (i * height+startY)/5+length+endbottom);
            }

            pdfCanvas.stroke();
            //绘制大网格竖线
            pdfCanvas.setStrokeColor(colorS).setLineWidth(0.2f);
            for (int i = 0; i < 51; i++) {
                pdfCanvas.moveTo(i * width+startY+length*5, startY+endbottom)
                        .lineTo(i * width+startY+length*5, endY+length+endbottom);
            }
            //多少次数、一次画6份 大网横线
            for (int i = 0; i <= (col * 6); i++) {
                pdfCanvas.moveTo(startX+startY+length*5, i * height+startY+endbottom)
                        .lineTo(endX+startY+length*5, i * height+startY+endbottom);
            }
            // pdfCanvas.stroke();
            //  pdfExtGState.setStrokeOpacity(1f);
            // pdfCanvas.setStrokeColor(colorS).setLineWidth(1f);


            //绘制时间标识



/*   for (int i = 0; i < 11; i++) {
                pdfCanvas.moveTo(i*5 * width+10, startY-20)
                        .lineTo(i*5 * width+10, endY);
                pdfCanvas.setTextMatrix(i*5 * width, startY-40);
                pdfCanvas.showText(i*12+"s");
            }*/



            pdfCanvas.stroke();
            pdfCanvas.setStrokeColor(new DeviceRgb(0,0,0));
            pdfCanvas.setLineWidth(0.35f);
            out:
            //绘制心率线2560

            for (int i = 0; i < col; i++) {
                int startPoint = i * maxXSize;
                for (int j = 0; j < maxXSize; j++) {
                    int x = j;
                    if (startPoint + j >= size) break out;
                    int y = data.get(startPoint + j);
                    if (j == 0) pdfCanvas.moveTo(startY+length*5, getCanvasY(y, i));
                    pdfCanvas.lineTo(x * endX / maxXSize+startY+length*5, getCanvasY(y, i));
                }
            }

            pdfCanvas.stroke();
            document.close();
            pdfDocument.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    //static String FONTS=MyApplication.context.getResources().getString(R.raw.zhengkai);
    private static void addParagraph(Document document,PdfCanvas pdfCanvas,String date,float totalHeight){
        pdfCanvas.setColor( DeviceRgb.BLACK,true);
        String account=SharePreferenceUtils.account_default;
        UserInfo userInfo= UserInfoDaoManager.getUser(account);
        try {
            PdfFontFactory.registerSystemDirectories();
            PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
            /*String yaHeiFontName = MyApplication.context.getResources().getString(R.raw.msyhl);
            yaHeiFontName += ",1";
            PdfFont font = PdfFontFactory.createFont(yaHeiFontName,PdfEncodings.IDENTITY_H, true);*///解决中文不显示*/
            pdfCanvas.setFontAndSize(font, 16);
            String name;
            if(TextUtils.isEmpty(userInfo.getName())){
                name="";
            }else{
                name=  userInfo.getName();
            }
            int gender=userInfo.getGender();
            //男女
            String genderString;
            if(LanguageHelp.isEnglish()){
                genderString=gender==0?"Male":"Female";
            }else{
                genderString=gender==0?"男":"女";
            }
            int age = userInfo.getAge();
            int userWeight=userInfo.getWeight();
            int userHeight=userInfo.getHeight();
            //标题
            if(LanguageHelp.isEnglish()){
                pdfCanvas.beginText().setFontAndSize(font, 18)
                        .moveText(totalWidth/2+((595/210)*10), endbottom+totalHeight+((595/210)*10))
                        .showText("ECG Report")
                        .endText();
            }else{
                pdfCanvas.beginText().setFontAndSize(font, 18)
                        .moveText(totalWidth/2+((595/210)*10), endbottom+totalHeight+((595/210)*10))
                        .showText("心电图报告")
                        .endText();
            }

            //提醒
            if(LanguageHelp.isEnglish()){
                pdfCanvas.beginText().setFontAndSize(font, 16)
                        .moveText(totalWidth -((595/210)*60), endbottom+totalHeight+((595/210)*15))
                        .showText("The report is for reference only ")
                        .endText();
            }else{
                pdfCanvas.beginText().setFontAndSize(font, 16)
                        .moveText(totalWidth-((595/210)*15), endbottom+totalHeight+((595/210)*13))
                        .showText("本报告仅供参考")
                        .endText();
            }
            //个人信息
            if(LanguageHelp.isEnglish()){
                pdfCanvas.beginText().setFontAndSize(font, 16)
                        .moveText(totalWidth/2-200, endbottom+totalHeight - ((595/210)*10))
                        .showText("Name: "+name+"  "+" Gender: "+genderString+"  "+
                                " Age: "+age+"  "+" Height: "+userHeight+"cm  "+"Weight: "+userWeight+"kg")
                        .endText();
            }else{
                pdfCanvas.beginText().setFontAndSize(
                        font, 16)
                        .moveText(totalWidth/2-150, endbottom+totalHeight - ((595/210)*10))
                        .showText("姓名: "+name+"  "+" 性别: "+genderString+"  "+
                                " 年龄: "+age+"  "+" 身高: "+userHeight+"cm  "+"体重: "+userWeight+"kg")
                        .endText();
            }
            pdfCanvas.stroke();
            //时间
            if(LanguageHelp.isEnglish()){
                String time = DateUtil.getFormatTimeString(Long.valueOf(date), "MM/dd/yyyy HH:mm");
                pdfCanvas.beginText().setFontAndSize(font, 10)
                        .moveText(totalWidth-((595/210)*3f), length*4 +((595/210)*2f))
                        .showText("Date: "+time)
                        .endText();
            }else{
                String time = DateUtil.getFormatTimeString(Long.valueOf(date), "yyyy/MM/dd HH:mm");
                pdfCanvas.beginText().setFontAndSize(font, 10)
                        .moveText(totalWidth-((595/210)*3f), length*4 +((595/210)*2f))
                        .showText("日期: "+time)
                        .endText();

            }
            MyBluetoothDevice myBluetoothDevice=SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS);
            String Name="";
            if(null!=myBluetoothDevice&&null!=myBluetoothDevice.getNames()){
                Name= myBluetoothDevice.getNames();
            }
            pdfCanvas.beginText().setFontAndSize(font, 10)
                    .moveText(totalWidth/2-((595/210)*40), length*4 +((595/210)*2f))
                    .showText("25mm/s    10mm/mV    0.5~40Hz    250Hz   Lead V5     ID:  "+Name.replace("EK_Health",""))
                    .endText();
            String time=DateUtil.getFormatTimeString(Long.valueOf(date.trim()),"yy.MM.dd HH:mm:ss");
            HrvData hrvData= HrvDataDaoManager.HrvData(time);
            pdfCanvas.stroke();
            if(null!=hrvData){
                if(LanguageHelp.isEnglish()){
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth+length+length/2, endbottom+totalHeight-((595/210)*17.5f))
                            .showText("Max: "+hrvData.getMaxHeart()+" bpm")
                            .endText();
                }else{
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth-((595/210)*5), endbottom+totalHeight-((595/210)*17.5f))
                            .showText("最高心率: "+hrvData.getMaxHeart()+" bpm")
                            .endText();
                }
                if(LanguageHelp.isEnglish()){
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth+length+length/2, endbottom+totalHeight-((595/210)*10f))
                            .showText("Avg: "+hrvData.getAvgHeart()+" bpm")
                            .endText();
                }else{
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth-((595/210)*5), endbottom+totalHeight-((595/210)*10f))
                            .showText("平均心率: "+hrvData.getAvgHeart()+" bpm")
                            .endText();
                }
                if(LanguageHelp.isEnglish()){
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth+length+length/2, endbottom+totalHeight-((595/210)*2.5f))
                            .showText("Min: "+hrvData.getMinHeart()+" bpm")
                            .endText();
                }else{
                    pdfCanvas.beginText().setFontAndSize(font, 12)
                            .moveText(totalWidth-((595/210)*5), endbottom+totalHeight-((595/210)*2.5f))
                            .showText("最低心率: "+hrvData.getMinHeart()+" bpm")
                            .endText();
                }
            }

        } catch (IOException e) {
            e.printStackTrace(); }
    }
    private static float getCanvasY(int value,int index) {
        float height;
      /*  if(0==index){
            height =((totalHeight+length+endbottom)-(length*3))+20;
        }else{
            height= (((totalHeight+length+endbottom)-index*((length*6)))-(length*3))+(value-98);
        }*/

        if(0==index){
            height =((totalHeight+length+endbottom)-(length*3))+Newvalue((value-93));
        }else{
            height= (((totalHeight+length+endbottom)-index*((length*6)))-(length*3))+Newvalue(value-93);
        }
        return height;
    }

    private static float Newvalue(final float value){
        float newvalue=((value*16f)-1602f)/767f;
        float small=value*newvalue;
        return   -small*(0.5f);


    }


}

